<template>
  <div class="main">

    <div :class="['common_app', { classify_content_fixed: isEditCommon }]">
      <div class="classify_content" ref="comTap">
        <p class="title">我的常用</p>
        <div class="word_content">
          <div v-for="(item, index) in commonApps.CHILD" :key="index" @click="!isEditCommon ? openApp(item) : editApp(item)" :class="[
              'word_app',
              { edit_checked_app: isEditCommon }
            ]">
            <div>
              <img class="app_icon" :src="'static/image/word/' + item.ICON + '.png'" />
              <span class="noRead" v-if="isShowNoRead(item)">{{ isShowNoRead(item) }}</span>
            </div>
            <span>{{ item.NAME }}</span>
            <img v-if="isEditCommon" class="app_selected" src="static/image/word/app_selected.png" />
          </div>
          <div class="word_app" @click="editCommon" v-if="!isEditCommon">
            <img class="app_icon" src="static/image/word/app_add.png" alt="" />
            <span class="edit_button">编辑应用</span>
          </div>
        </div>
      </div>
    </div>
    <div ref="tapp" :class="['others_app', { others_app_top: isEditCommon }]">
      <div class="classify_content edit_app" v-for="(item, index) in othersApps" :key="index">
        <p class="title">{{ item.NAME }}</p>
        <div class="word_content">
          <div @click="isEditCommon ? editApp(item1) : openApp(item1, index1)" :class="[
            'word_app',
            { edit_checked_app: isEditCommon && isCommonApp(item1.NAME) },
            { edit_nochecked_app: isEditCommon && !isCommonApp(item1.NAME) },
          ]" v-for="(item1, index1) in item.CHILD" :key="index1">
            <div>
              <div class="showLoading" v-if="item1.loading == 1">
                <span class="percent">{{ item1.progress }}</span>
                <div class="progress" :style="{ width: item1.progress, height: '8px', 'border-radius': '10px', 'background-color': 'green', border: '1px solid green' }">
                </div>
              </div>

              <img v-else class="app_icon" :src="'static/image/word/' + item1.ICON + '.png'" alt="" />
              <div v-if="item1.NAME == 'NFC读卡器' && nfcControl == true" style="position:absolute;bottom:2px;" class="app_icon">
                <img src="static/image/word/app_run.png">
              </div>
              <span class="noRead" v-if="isShowNoRead(item1)">{{ isShowNoRead(item1) }}</span>
            </div>

            <span v-if="item1.loading == 0">{{ item1.NAME }}</span>
            <img v-if="isEditCommon && !isCommonApp(item1.NAME)" class="app_selected" src="static/image/word/app_select.png" />
            <img v-if="isEditCommon && isCommonApp(item1.NAME)" class="app_selected" src="static/image/word/app_selected.png" alt="" />
          </div>
        </div>
      </div>
    </div>
    <div class="foot" v-if="isEditCommon">
      <div class="foot-button confirm-button" @click="confirmCommon">确定</div>
      <div class="foot-button cancel-button" @click="cancelEditCommon">
        取消
      </div>
    </div>

  </div>
</template>

<script>
import { mapState } from "vuex";
import { findAll_axios, editUserApp_axios } from "@/api/wordbench";
export default {
  name: "",
  props: {
    workList: {
      type: Array,
      default: [],
    }, //办公事务
    officialManageTotal: {
      type: Number,
      default: 0,
    },
  },

  data() {
    return {
      downCount: 2,
      downLoadPluginList: [],
      PluginWaitingList: [],
      msg: "0.00%",
      loadingIndex: -1,
      loading: false,
      isClick: true,
      plugin: {},
      isEditCommon: false, //是否编辑常用
      othersApps: [], //其他应用
      commonApps: [], //常用应用
      oldCommonApps: [], //临时存储常用应用
      nfcControl: false,
    };
  },
  components: {},
  computed: {
    ...mapState(["myInfo", "icReadDriveOpen"]),

    // test1() {
    //   return this.test();
    // },
  },
  beforeMount() {
    /* 新增插件下载  */
    window.checkPluginStatus = this.checkPluginStatus;
    window.downloadProcess = this.downloadProcess;
    window.isWaitingDownLoad = this.isWaitingDownLoad;
    window.readCarErrorInfo = this.readCarErrorInfo;
    window.openIcReadCarState = this.openIcReadCarState;
    window.closeIcReadCarState = this.closeIcReadCarState;
    // 判断插件是否已经下载
    window.pluginIsDownload = this.pluginIsDownload;
    findAll_axios({ userid: this.myInfo.id }).then((res) => {
      //获取所有应用
      res[0].CHILD = res[0].CHILD ? res[0].CHILD : [];
      this.commonApps = res[0];
      if (!this.myInfo.article) {
        const index = res[1].CHILD.findIndex((item) => {
          return item.URL;
        });
        res[1].CHILD.splice(index, 1);
        // console.log(res[1]);
      }
      let othersApps = res.slice(1);

      othersApps.forEach((i) => {
        if (i.NAME == "办公事务" || i.NAME == "办公管理") {
          i.CHILD.push({
            NAME: "自助机后台",
            ICON: "zizhuji",
          });
        }
        i.CHILD = i.CHILD.map((item) => {
          return {
            ...item,
            loading: 0,
            isClick: 1,
            isWaiting: 0,
            progress: "0.00%",
          };
        });
      });
      this.commonApps.CHILD.forEach((item) => {
        item["isClick"] = 1;
      });
      this.othersApps = othersApps;
      console.log(this.othersApps, 12000000);
    });
  },

  mounted() {
    var _this = this;
    var elementResizeDetectorMaker = require("element-resize-detector"); //导入
    // 创建实例
    var erd = elementResizeDetectorMaker();
    //监听id为test的元素 大小变化
    erd.listenTo(
      document.getElementsByClassName("common_app")[0],
      function (element) {
        var height = element.offsetHeight;
        _this.$nextTick(function () {
          if (_this.isEditCommon) {
            _this.$refs.tapp.style.marginTop = height + "px";
          } else {
            _this.$refs.tapp.style.marginTop = 0 + "px";
          }
        });
      }
    );
  },

  methods: {
    // getApp() {
    //   console.log(this.othersApps[0].CHILD);
    // },
    openIcReadCarState(result) {
      if (result == true || result == "True") {
        this.nfcControl = true;
        this.$message({
          type: "success",
          message: "启动NFC读卡器",
        });
        this.$store.commit("setIcReadDriveOpen", true);
      }
    },
    closeIcReadCarState(result) {
      if (result == true || result == "True") {
        this.nfcControl = false;
        this.$message({
          type: "success",
          message: "关闭NFC读卡器",
        });
        this.$store.commit("setIcReadDriveOpen", false);
      }
    },
    // 2022/4/15 zc新增 操作NFC读卡器失败外壳回调
    readCarErrorInfo(message) {
      let messageArr = message.split("：");
      let mes = messageArr.slice(-1);
      this.$message({
        type: "warning",
        message: `操作读卡器失败：${mes}`,
      });
    },
    pluginIsDownload(PLUGINNAME) {
      this.othersApps[0].CHILD.forEach((item) => {
        if (item.PLUGINNAME == PLUGINNAME) {
          item.isDownload = true;
          this.openApp(item);
        }
      });
    },
    isWaitingDownLoad(count) {
      console.log(count);
      if (count < 0) {
        this.$message({
          type: "error",
          message: "超过最大下载次数",
        });
        this.plugin.isClick = 1;
      } else {
        this.plugin.loading = 1;
        this.$message({
          type: "success",
          message: "后台开始下载，升级中!",
        });
        this.downCount--;
        this.downLoadPluginList.push(this.plugin);
      }
    },
    //2022/4/25 zc修改插件更新
    checkPluginStatus(message, result) {
      console.log(message, result, "是否需要更新");

      if (result == "404") {
        this.$message({
          type: "warn",
          message: "当前网络不稳定,请等待!",
        });
      }
      console.log(message, "是否需要更新");
      if (message == 0) {
        this.plugin.isClick = 1;
      } else {
        this.plugin.loading = 1;
      }
    },

    downloadProcess(message, name) {
      console.log(message, name, "进度");
      if (message != "下载中" && message != "下载完成") {
        // this.msg = message;
        this.downLoadPluginList.forEach((t) => {
          if (t.PLUGINNAME == name) {
            t.progress = message;
          }
        });
      }
      if (message == "下载中") {
        if (name) {
          this.downLoadPluginList.forEach((i) => {
            if (i.PLUGINNAME == name) {
              console.log(name, 204);
              i.loading = 1;
            }
          });
        }
        console.log(message, "更新进度");
      } else if (message == "下载完成") {
        this.$message({
          type: "success",
          message: "下载完成",
        });
        this.downCount++;
        console.log(message, name, "更新进度");
        if (name) {
          this.downLoadPluginList.forEach((i) => {
            if (i.PLUGINNAME == name) {
              console.log(name, 204);
              i.isClick = 1;
              i.loading = 0;
              i.isDownload = true;
            }
          });
        }
        // let downLoadPluginList = this.downLoadPluginList.filter((i) => {
        //   return i != message.name;
        // });
        // if (downLoadPluginList.length < 3) {
        //   if (this.PluginWaitingList[0]) {
        //     this.$downloadPlug("PluginUpdateAndDownload", [
        //       this.PluginWaitingList[0],
        //     ]);
        //     downLoadPluginList.push(this.PluginWaitingList[0]);
        //     this.PluginWaitingList.splice(0, 1);
        //   }
        // }

        // this.downLoadPluginList = downLoadPluginList;

        // this.$emit("transmitAppName", this.plugin);
      } else if (message == "下载失败") {
        this.downCount++;
        this.$message({
          type: "error",
          message: "下载失败",
        });
        this.downLoadPluginList.forEach((i) => {
          if (i.PLUGINNAME == name) {
            console.log(name, 204);
            i.isClick = 1;
            i.loading = 0;
          }
        });
      }
    },
    editCommon() {
      //点击编辑应用
      this.isEditCommon = true;
      this.oldCommonApps = JSON.parse(JSON.stringify(this.commonApps));
      this.$refs.tapp.style.marginTop = this.$refs.comTap.offsetHeight + "px";
    },
    cancelEditCommon() {
      //取消编辑应用
      this.commonApps = JSON.parse(JSON.stringify(this.oldCommonApps));
      this.isEditCommon = false;
      this.$refs.tapp.style.marginTop = 0 + "px";
    },
    openApp(item) {
      console.log(item);
      //打开APP
      // if (item.isClick) {
      //
      // } else {
      //   console.log("未下载完成");
      // }
      // 判断是否为插件
      if (item.ISPLUGIN == "1" && item.PLUGINNAME) {
        // 判断插件是否下载
        if (!item.isDownload) {
          if (this.downCount < 0)
            return this.$message({
              type: "error",
              message: "超过最大下载次数",
            });
          item.isClick = 0;
          this.plugin = item;
          console.log(item.PLUGINNAME, "调取外壳更新插件接口");
          this.$downloadPlug("PluginUpdateAndDownload", [
            item.PLUGINNAME,
            "",
            "",
            "",
            "",
          ]);
        } else {
          if (item.NAME == "NFC读卡器") {
            if (this.nfcControl == false) {
              this.$downloadPlug("PluginUpdateAndDownload", [
                "UMP_Plugin_ICReadDrive",
                "MethodList",
                "Open",
                "",
                "",
              ]);
            } else {
              this.$downloadPlug("PluginUpdateAndDownload", [
                "UMP_Plugin_ICReadDrive",
                "MethodList",
                "Close",
                "",
                "",
              ]);
            }
          }
          if (item.NAME == "透传服务") {
            this.$downloadPlug("PluginUpdateAndDownload", [
              item.PLUGINNAME,
              "",
              "",
              item.URL,
              "exe",
            ]);
          }
        }
      } else {
        this.$emit("transmitAppName", item);
      }
    },
    isCommonApp(name) {
      //判断该应用是否是常用应用
      return this.commonApps.CHILD.some((val) => {
        return val.NAME == name;
      });
    },
    editApp(item) {
      //点击APP改变状态
      let flag = this.commonApps.CHILD.some((val) => {
        return val.NAME == item.NAME;
      });
      if (flag) {
        this.commonApps.CHILD.forEach((val, index) => {
          if (val.NAME == item.NAME) {
            return this.commonApps.CHILD.splice(index, 1);
          }
        });
      } else {
        if (this.commonApps.CHILD.length >= 9) {
          this.$Message.warning("常用应用最多设置9个");
          return false;
        } else {
          return this.commonApps.CHILD.push(item);
        }
      }
    },
    confirmCommon() {
      //提交修改常用
      let appArr = [];
      this.commonApps.CHILD.forEach((val) => {
        appArr.push(val.ID);
      });
      let appids = appArr.join(",");
      editUserApp_axios({ userid: this.myInfo.id, appids: appids })
        .then((res) => {
          if (res.code == 200) {
            this.isEditCommon = false;
            this.$Message.success("设置成功");
          } else {
            this.commonApps = JSON.parse(JSON.stringify(this.oldCommonApps));
          }
        })
        .catch((error) => {
          this.commonApps = JSON.parse(JSON.stringify(this.oldCommonApps));
        });
    },
    isShowNoRead(item) {
      let num = 0;
      if (
        item.NAME == "广播通知" &&
        this.workList[1].noRead &&
        this.workList[1].noRead > 0
      ) {
        num = this.workList[1].noRead;
        return num > 99 ? "99+" : num;
      } else if (
        item.NAME == "我的待办" &&
        this.officialManageTotal &&
        this.officialManageTotal > 0
      ) {
        num = this.officialManageTotal;
        return num > 99 ? "99+" : num;
      }
      return false;
    },
  },
  watch: {
    "reqLoading.state"(v) {
      console.log(v, 45111111);
    },
  },
};
</script>
<style lang="less" scoped>
.main {
  height: 100vh;
  width: calc(100vw - 56px);
  overflow: scroll;

  .common_app {
    width: 100%;
    background-color: white;
    padding: 0px 15px;
  }

  .classify_content_fixed {
    position: fixed !important;
    background-color: #f5f5f5;
    z-index: 23;
    width: calc(100% - 56px);
    min-height: 100px;
  }

  .foot {
    position: fixed;
    bottom: 0px;
    height: 40px;
    width: 100%;
    box-shadow: 0px -4px 8px 0px rgba(0, 0, 0, 0.2);
    z-index: 22;
    background: white;
    width: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-right: 56px;

    .foot-button {
      cursor: pointer;
      width: 46px;
      height: 26px;
      margin-right: 10px;
      text-align: center;
      border-radius: 4px;
      line-height: 23px;
      font-size: 12px;
    }

    .confirm-button {
      border: 1px solid #fa7500;
      background-color: #fa7500;
      color: #ffffff;
    }

    .cancel-button {
      border: 1px solid #dddddd;
      background-color: #dddddd;
      color: #666666;
    }
  }

  .others_app_top {
    margin-bottom: 50px;
    margin-top: 100px;
  }

  .others_app {
    padding: 10px 15px;
    width: 100%;
  }

  .classify_content {
    padding: 10px 0px;

    .title {
      color: #333333;
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 10px;
    }

    .word_content {
      display: flex;
      flex-wrap: wrap;

      .showLoading {
        position: relative;
        width: 80px;
        height: 8px;
        // padding-top: 15px;
        border-radius: 10px;
        border: 1px solid green;
        margin-top: 10px;
        // overflow: hidden;

        .progress {
          position: absolute;
          top: -1px;
          left: 0;
        }

        .percent {
          position: absolute;
          top: -22px;
          left: 19px;
        }
      }

      .edit_checked_app {
        border: 1px #ffac00 dashed;
        border-radius: 8px;
        background-color: #fff8eb;
      }

      .edit_nochecked_app {
        border: 1px #cccccc dashed;
        border-radius: 8px;
      }

      .word_app {
        cursor: pointer;
        height: 40px;
        min-width: 140px;
        margin: 10px 0px;
        margin-right: 20px;
        display: flex;
        align-items: center;
        position: relative;
        font-size: 12px;

        .app_icon {
          width: 40px;
          height: 40px;
          margin-right: 10px;
        }

        .noRead {
          padding: 0 5px;
          background: #ff0909;
          border-radius: 12px;
          color: white;
          box-shadow: -2px 2px 4px 0 rgba(0, 0, 0, 0.2);
          position: absolute;
          top: -10px;
          left: 30px;
        }

        .app_selected {
          width: 12px;
          height: 12px;
          margin-left: 20px;
          margin-right: 10px;
        }

        .edit_button {
          color: #fa7500;
        }
      }
    }
  }
}
</style>
